/**
 * Created by jackliu on 15/12/16.
 */

var common = require('../../common');
var pool = require('../index');
var mysql = require('mysql');
var ItbBaseModel = require('./ItbBaseModel');


// Schema 结构
var TgUserPcModel = function(obj){
    ItbBaseModel.call(this,obj);

  // 以下为表定义数据，需要的字段就填入
  //`pc_id` bigint(20) unsigned NOT NULL AUTO_INCREMENT COMMENT 'id',
  //`doc_id` bigint(20) unsigned NOT NULL COMMENT '文档ID',
  //`page_id` bigint(20) unsigned NOT NULL COMMENT '文档页ID',
  //`pc_index` int(3) NOT NULL DEFAULT '0' COMMENT '下标（0开始）',
  //`backup_flg` int(1) NOT NULL DEFAULT '0' COMMENT '0普通页; 1保留页',
  //`data` mediumtext COMMENT '模版页内容',
  //`replaces` mediumtext COMMENT '可替换组',
  //`hash_tag` varchar(100) DEFAULT '0' COMMENT '标记',
  //`thumb_s` text COMMENT '缩略图小',
  //`thumb_m` text COMMENT '缩略图中',
  //`thumb_l` text COMMENT '缩略图大',
  //`audio` text COMMENT '音频url数组',
  //`video` text COMMENT '视频url数组',
  //`media` text COMMENT '原始视频',
  //`dirty` int(1) NOT NULL DEFAULT '0' COMMENT '0未修改; 1页被修改过',
  //`create_time` datetime NOT NULL,
  //`update_time` datetime NOT NULL,
  //`update_by` varchar(50) NOT NULL DEFAULT '',
  //`del_flg` int(1) NOT NULL DEFAULT '0',

};
TgUserPcModel.prototype = new ItbBaseModel();

// 取得表名
TgUserPcModel.prototype.getTableName = function(){
    return 'tg_user_pc';
}
// 取得查询语句中where 后面匹配主键的条件（需要各派生类进行重载）
TgUserPcModel.prototype.getWhereConditionOfKeyEqual = function(){
    return 'pc_id='+this.pc_id;
}

// 取得排序方法（需要各派生类进行重载）
TgUserPcModel.prototype.getOrderBy = function(){
    return ' pc_index asc ';
}

//------------------------------------------------------------------
// 根据doc_id/page_id/pc_id逻辑删除对应pc
TgUserPcModel.prototype.delPcLogic = function(callback){
    var THIS = this;
    var tableName = this.getTableName();

    pool.pool.getConnection(function(err, connection) {
        // Use the connection
        var sql = 'UPDATE tg_user_pc '+
            ' SET del_flg=1, update_time=sysdate(), update_by= '+THIS.update_by+
            ' WHERE del_flg = 0 ';
        var config=false;
        if(typeof THIS.doc_id!='undefined' && THIS.doc_id != null) {
            sql += ' AND doc_id= '+ THIS.doc_id;
            config=true;
        }
        if(typeof THIS.page_id!='undefined' && THIS.page_id != null) {
            sql += ' AND page_id= '+ THIS.page_id;
            config=true;
        }
        if(typeof THIS.pc_id!='undefined' && THIS.pc_id != null) {
            sql += ' AND pc_id= '+ THIS.pc_id;
            config=true;
        }
        if(!config){
            return callback("却少参数");
        }

        //var sqlValue = [THIS.update_by, THIS.doc_id];
        //var sql = mysql.format(sql, sqlValue);
        connection.query(sql, function(error, result) {
            // And done with the connection.
            connection.release();
            console.log();

            if(error) {
                callback(error);
            } else {
                callback(null);
            }
        });
    });
}
//------------------------------------------------------------------
//------------------------------------------------------------------
// 根据doc_id/page_id逻辑删除pc_index大于指定值的对应pc
TgUserPcModel.prototype.delPcLogicOfOtherPcIndex = function(callback){
    var THIS = this;
    var tableName = this.getTableName();

    pool.pool.getConnection(function(err, connection) {
        // Use the connection
        var sql = 'UPDATE tg_user_pc '+
            ' SET del_flg=1, update_time=sysdate(), update_by= '+THIS.update_by+
            ' WHERE del_flg = 0 ';

        sql += ' AND doc_id= '+ THIS.doc_id;
        sql += ' AND page_id= '+ THIS.page_id;
        sql += ' AND pc_index!= '+ THIS.pc_index;


        //var sqlValue = [THIS.update_by, THIS.doc_id];
        //var sql = mysql.format(sql, sqlValue);
        connection.query(sql, function(error, result) {
            // And done with the connection.
            connection.release();
            console.log();

            if(error) {
                callback(error);
            } else {
                callback(null);
            }
        });
    });
}
//------------------------------------------------------------------



//------------------------------------------------------------------
// 根据doc_id/page_id/pc_index将pc_index设置为0
TgUserPcModel.prototype.updatePcIndexToFirst = function(callback){
    var THIS = this;
    var tableName = this.getTableName();

    pool.pool.getConnection(function(err, connection) {
        // Use the connection
        var sql = 'UPDATE tg_user_pc '+
            ' SET update_time=sysdate(), update_by= '+THIS.update_by+ ',pc_index=0 '+
            ' WHERE del_flg = 0 ';

        sql += ' AND doc_id= '+ THIS.doc_id;
        sql += ' AND page_id= '+ THIS.page_id;
        sql += ' AND pc_index= '+ THIS.pc_index;


        //var sqlValue = [THIS.update_by, THIS.doc_id];
        //var sql = mysql.format(sql, sqlValue);
        connection.query(sql, function(error, result) {
            // And done with the connection.
            connection.release();
            console.log();

            if(error) {
                callback(error);
            } else {
                callback(null);
            }
        });
    });
}
//------------------------------------------------------------------


//------------------------------------------------------------------
// 复制设计模版的pc信息 到新的用户文档
TgUserPcModel.prototype.copyPcFromDesign = function(callback, designId){
    var THIS = this;

    pool.pool.getConnection(function(err, connection) {
        // Use the connection
        var sql =
            " INSERT INTO TG_USER_PC "+
            " (doc_id, page_id, design_pc_id, pc_index, backup_flg, data, replaces, hash_tag, "+
            " thumb_s, audio, video, media, dirty, create_time, update_time, update_by, del_flg) "+
            " SELECT up.doc_id, up.page_id, t.pc_id, t.pc_index, t.backup_flg, t.data, t.replaces, t.hash_tag, "+
            " null, t.audio, t.video, t.media, t.dirty, sysdate(), sysdate(), " +THIS.update_by +", 0 "+
            " FROM TG_DESIGN_PC t, TG_USER_PAGE up "+
            " WHERE t.del_flg=0 AND t.design_id = " +designId+
            " AND up.del_flg=0 AND up.doc_id = " +THIS.doc_id+
            " AND up.design_page_id = t.page_id ";

        //var sqlValue = [ THIS.docId, THIS.designId ];
        //var sql = mysql.format(sql, sqlValue);
        console.log(sql);
        connection.query(sql, function(error, result) {
            // And done with the connection.
            connection.release();

            if (error)
                console.log(error);

            callback(error);
        });
    });
}
//------------------------------------------------------------------

//------------------------------------------------------------------
// 复制设计模版的pc信息 到已存在用户文档
TgUserPcModel.prototype.updPcFromDesign = function(callback, designId){
    var THIS = this;

    pool.pool.getConnection(function(err, connection) {
        // Use the connection
        var sql =
            " UPDATE TG_USER_PC t, TG_DESIGN_PC d "+
            " SET t.data=d.data, t.hash_tag=d.hash_tag, t.replaces=d.replaces, t.thumb_s=null, "+
            " t.update_time=sysdate(), t.update_by="+ THIS.update_by+
            " WHERE t.del_flg=0 AND t.doc_id=" +THIS.doc_id+
            " AND d.del_flg=0 AND d.design_id=" +designId+
            " AND t.design_pc_id=d.pc_id AND t.pc_index=d.pc_index ";

        //var sqlValue = [ THIS.docId, THIS.designId ];
        //var sql = mysql.format(sql, sqlValue);
        console.log(sql);
        connection.query(sql, function(error, result) {
            // And done with the connection.
            connection.release();

            if (error)
                console.log(error);

            callback(error);
        });
    });
}
//------------------------------------------------------------------

//------------------------------------------------------------------
// 根据doc_id/page_id/pc_id清除预览图
TgUserPcModel.prototype.clrPcThumb = function(callback){
    var THIS = this;
    var tableName = this.getTableName();

    pool.pool.getConnection(function(err, connection) {
        // Use the connection
        var sql = 'UPDATE tg_user_pc '+
            ' SET thumb_s=null, thumb_m=null, thumb_l=null, update_time=sysdate(), update_by= '+THIS.update_by+
            ' WHERE del_flg = 0 ';
        if(typeof THIS.doc_id!='undefined' && THIS.doc_id != null) {
            sql += ' AND doc_id= '+ THIS.doc_id;
        }
        if(typeof THIS.page_id!='undefined' && THIS.page_id != null) {
            sql += ' AND page_id= '+ THIS.page_id;
        }
        if(typeof THIS.pc_id!='undefined' && THIS.pc_id != null) {
            sql += ' AND pc_id= '+ THIS.pc_id;
        }

        //var sqlValue = [THIS.update_by, THIS.doc_id];
        //var sql = mysql.format(sql, sqlValue);
        connection.query(sql, function(error, result) {
            // And done with the connection.
            connection.release();
            console.log();

            if(error) {
                callback(error);
            } else {
                callback(null);
            }
        });
    });
}
//------------------------------------------------------------------
// 按pageindex排序
// callback 参数：
//                error：错误
//                items：找到所有对象
ItbBaseModel.prototype.findFromDBOrderByPageIndex = function(callback){
    var THIS = this;

    // 从mysql中查询
    pool.pool.getConnection(function(err, connection) {
        var sql = 'select a.*,b.page_index from tg_user_pc a,tg_user_page b '+
        ' where a.doc_id = '+THIS.doc_id+
        ' and a.del_flg=0 '+
        ' and b.doc_id= '+THIS.doc_id+
        ' and b.del_flg=0 '+
        ' and a.page_id=b.page_id '+
        ' order by b.page_index asc, a.pc_index asc ';

        // Use the connection
        connection.query(sql, function(error, items) {
            // And done with the connection.
            connection.release();

            // 回调
            callback(error, items);
        });

    });

}
//------------------------------------------------------------------


// 导出
module.exports = TgUserPcModel;